import { useState } from 'react';

import { OrganizationData } from '../api/organization/organization';
import OrganizationManager from '../api/organization/organization-manager';
import { IFilter } from '../components/shared/tables/search-sort-paging-header';

export function useLoadPendingOrganisation(
    status: number,
    { paging, search, sortDirection, sortField }: IFilter
) {
    const [loading, setLoading] = useState(false);
    const [items, setItems] = useState<OrganizationData[]>([]);
    const [page, setPage] = useState(0);
    const [hasNextPage, setHasNextPage] = useState(false);
    const [error, setError] = useState<{ code: number; message: string }>(undefined);
    async function loadMore() {
        setLoading(true);
        try {
            const result = await OrganizationManager.getAllOrganization(
                status,
                page,
                paging,
                sortField,
                sortDirection,
                search
            );
            const { pending_organzizations, no_more_results } = result;
            setItems((current) => [...current, ...(pending_organzizations || [])]);
            setHasNextPage(!no_more_results);
            !no_more_results && setPage(page + 1);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    }

    return { loading, items, hasNextPage, error, loadMore };
}
